<template>
	<view class="container">
		<view class="profile-header">
			<view class="avatar-section">
				<image class="avatar" :src="userInfo.avatar || '/static/images/default-avatar.png'" mode="aspectFill" @click="chooseAvatar"></image>
				<text class="edit-avatar">更换头像</text>
			</view>
			
			<view class="basic-info">
				<view class="username">{{userInfo.nickname || userInfo.username}}</view>
				<view class="user-role">{{userRoleText}}</view>
			</view>
		</view>
		
		<view class="form-section">
			<view class="section-title">基本资料</view>
			
			<view class="form-item">
				<text class="form-label">姓名</text>
				<input class="form-input" type="text" v-model="userInfo.nickname" placeholder="请输入真实姓名，用于考试记录" required />
				<text class="required-mark">*</text>
			</view>
			
			<view class="form-item">
				<text class="form-label">手机号</text>
				<input class="form-input" type="number" v-model="userInfo.mobile" placeholder="请输入手机号" maxlength="11" />
			</view>
			
			<view class="form-item">
				<text class="form-label">邮箱</text>
				<input class="form-input" type="text" v-model="userInfo.email" placeholder="请输入邮箱" />
			</view>
			
			<view class="form-item">
				<text class="form-label">性别</text>
				<picker class="form-picker" @change="bindGenderChange" :value="genderIndex" :range="genderArray">
					<view class="picker-text">{{genderArray[genderIndex]}}</view>
				</picker>
			</view>
			
			<view class="form-item">
				<text class="form-label">出生日期</text>
				<picker class="form-picker" mode="date" :value="userInfo.birthday" @change="bindDateChange">
					<view class="picker-text">{{userInfo.birthday || '请选择出生日期'}}</view>
				</picker>
			</view>
		</view>
		
		<button class="save-btn" @click="saveProfile">保存资料</button>
	</view>
</template>

<script>
	import { getToken } from '../../utils/tokenManager.js';
	
	export default {
		data() {
			return {
				userInfo: {
					_id: '',
					username: '',
					nickname: '',
					mobile: '',
					email: '',
					avatar: '',
					gender: 0, // 0-未设置 1-男 2-女
					birthday: '',
					role: 'referee' // referee-裁判员 admin-裁判监督
				},
				genderArray: ['未设置', '男', '女'],
				genderIndex: 0
			}
		},
		computed: {
			userRoleText() {
				return this.userInfo.role === 'referee' ? '裁判员' : '裁判监督';
			}
		},
		onLoad() {
			// 获取用户信息
			this.getUserInfo();
			// 获取学习统计
			this.getLearningStatistics();
		},
		onShow() {
			// 如果已经加载了用户信息，则刷新证书信息
			if (this.userInfo && this.userInfo._id) {
				if (this.userInfo.role === 'referee' || this.userInfo.role === 1) {
					console.log('页面显示，刷新裁判信息');
					this.getRefereeInfo();
				} else if (this.userInfo.role === 'admin' || this.userInfo.role === 2) {
					console.log('页面显示，刷新监督信息');
					this.getadminInfo();
				}
			}
		},
		methods: {
			// 获取用户信息
			getUserInfo() {
				uni.showLoading({
					title: '加载中...'
				});
				
				// 首先尝试从本地存储获取用户信息
				const userInfoStr = uni.getStorageSync('userInfo');
				if (userInfoStr) {
					try {
						const localUserInfo = JSON.parse(userInfoStr);
						console.log('从本地存储获取到用户信息:', localUserInfo);
						
						// 更新用户信息
						this.updateUserInfo(localUserInfo);
						uni.hideLoading();
						return;
					} catch (e) {
						console.error('解析本地用户信息失败', e);
					}
				}
				
				// 如果本地存储没有用户信息，再尝试从云端获取
				(async () => {
					try {
						const userService = uniCloud.importObject('user-service');
						const res = await userService.getUserInfo(getToken());
						
						if (res.code === 0) {
							console.log('从云对象获取到用户信息:', res.data);
							this.updateUserInfo(res.data.userInfo);
						} else {
							// 如果云对象不可用，使用模拟数据
							console.log('云对象返回错误，使用模拟数据');
							this.getMockUserInfo();
						}
					} catch (err) {
						console.error('获取用户信息失败', err);
						// 如果云对象不可用，使用模拟数据
						console.log('调用云对象失败，使用模拟数据');
						this.getMockUserInfo();
					} finally {
						uni.hideLoading();
					}
				})();
			},
			
			// 更新用户信息的统一方法
			updateUserInfo(userData) {
				// 复制基本信息
				this.userInfo = {
					...this.userInfo,
					...userData
				};
				
				// 确保必要的字段存在
				this.userInfo._id = this.userInfo._id || '1';
				this.userInfo.username = this.userInfo.username || userData.account || '';
				this.userInfo.nickname = this.userInfo.nickname || userData.nickname || '';
				
				// 确保手机号和邮箱正确
				// 优先使用mobile字段，如果不存在则尝试使用phone字段
				if (userData.mobile) this.userInfo.mobile = userData.mobile;
				else if (userData.phone) this.userInfo.mobile = userData.phone;
				
				// 设置email字段
				if (userData.email) this.userInfo.email = userData.email;
				
				// 为方便后端兼容，同时设置phone字段
				this.userInfo.phone = this.userInfo.mobile;
				
				// 设置性别索引
				this.genderIndex = this.userInfo.gender || 0;
				
				console.log('用户信息已更新:', this.userInfo);
			},
			// 获取裁判信息
			async getRefereeInfo() {
				// 显示加载提示
				uni.showLoading({
					title: '获取裁判信息...',
					mask: true
				});
				
				try {
					const credentialService = uniCloud.importObject('credential-service');
					const res = await credentialService.getRefereeInfo({
						_id: this.userInfo._id
					});
					
					uni.hideLoading();
					if (res.code === 0) {
						console.log('获取裁判信息成功:', res.data);
						this.refereeInfo = res.data.refereeInfo;
						this.levelIndex = this.refereeInfo.level || 0;
						
						// 更新本地状态
						if (this.refereeInfo.status === 'approved') {
							console.log('证书已审核通过，更新显示');
						} else {
							console.log('证书状态:', this.refereeInfo.status);
						}
					} else {
						console.log('获取裁判信息失败:', res.message);
						this.getMockRefereeInfo();
					}
				} catch (err) {
					uni.hideLoading();
					console.error('获取裁判信息失败', err);
					this.getMockRefereeInfo();
				}
			},
			
			// 获取监督信息
			async getadminInfo() {
				// 显示加载提示
				uni.showLoading({
					title: '获取监督信息...',
					mask: true
				});
				
				try {
					const adminService = uniCloud.importObject('admin-service');
					const res = await adminService.getAdminInfo({
						_id: this.userInfo._id
					});
					
					uni.hideLoading();
					if (res.code === 0) {
						console.log('获取监督信息成功:', res.data);
						this.adminInfo = res.data.adminInfo;
						this.adminLevelIndex = this.adminInfo.level || 0;
						
						// 更新本地状态
						if (this.adminInfo.status === 'approved') {
							console.log('监督证书已审核通过，更新显示');
						} else {
							console.log('监督证书状态:', this.adminInfo.status);
						}
					} else {
						console.log('获取监督信息失败:', res.message);
						this.getMockadminInfo();
					}
				} catch (err) {
					uni.hideLoading();
					console.error('获取监督信息失败', err);
					this.getMockadminInfo();
				}
			},
			
			// 获取模拟监督信息
			getMockadminInfo() {
				this.adminInfo = {
					level: 1,
					years: '8',
					certificate_no: 'SUP20150001',
					issue_date: '2015-03-20',
					status: 'pending' // 默认设为待审核，这样就不会显示
				};
				this.adminLevelIndex = this.adminInfo.level || 0;
			},
			
			// 获取模拟裁判信息
			getMockRefereeInfo() {
				this.refereeInfo = {
					level: 1,
					years: '5',
					certificate_no: 'REF20180001',
					issue_date: '2018-05-15',
					status: 'pending' // 默认设为待审核
				};
				this.levelIndex = this.refereeInfo.level || 0;
			},
			
			// 选择头像
			chooseAvatar() {
				// 首先检查是否有权限
				uni.getSetting({
					success: (res) => {
						// 检查相机权限
						if (res.authSetting['scope.camera'] === false) {
							uni.showModal({
								title: '权限申请',
								content: '需要获取您的相机权限来拍摄头像，请在设置中开启',
								confirmText: '去设置',
								success: (modalRes) => {
									if (modalRes.confirm) {
										uni.openSetting();
									}
								}
							});
							return;
						}
						
						// 选择图片
						uni.chooseImage({
							count: 1,
							sizeType: ['compressed'],
							sourceType: ['album', 'camera'],
							success: (res) => {
								const tempFilePath = res.tempFilePaths[0];
								
								// 检查文件大小（限制5MB）
								uni.getFileInfo({
									filePath: tempFilePath,
									success: (fileInfo) => {
										const fileSize = fileInfo.size / 1024 / 1024; // 转换为MB
										if (fileSize > 5) {
											uni.showToast({
												title: '图片大小不能超过5MB',
												icon: 'none'
											});
											return;
										}
										
										// 上传头像
										this.uploadAvatar(tempFilePath);
									},
									fail: (err) => {
										console.error('获取文件信息失败', err);
										// 如果获取文件信息失败，仍然尝试上传
										this.uploadAvatar(tempFilePath);
									}
								});
							},
							fail: (err) => {
								console.error('选择图片失败', err);
								if (err.errMsg && err.errMsg.includes('cancel')) {
									// 用户取消选择，不显示错误
									return;
								}
								uni.showToast({
									title: '选择图片失败，请重试',
									icon: 'none'
								});
							}
						});
					},
					fail: (err) => {
						console.error('获取权限设置失败', err);
						// 即使获取权限设置失败，仍然尝试选择图片
						uni.chooseImage({
							count: 1,
							sizeType: ['compressed'],
							sourceType: ['album', 'camera'],
							success: (res) => {
								const tempFilePath = res.tempFilePaths[0];
								this.uploadAvatar(tempFilePath);
							},
							fail: (err) => {
								console.error('选择图片失败', err);
								uni.showToast({
									title: '选择图片失败，请重试',
									icon: 'none'
								});
							}
						});
					}
				});
			},
			
			// 上传头像
			uploadAvatar(filePath) {
				uni.showLoading({
					title: '上传中...',
					mask: true
				});
				
				// 检查网络状态
				uni.getNetworkType({
					success: (res) => {
						if (res.networkType === 'none') {
							uni.hideLoading();
							uni.showToast({
								title: '网络连接异常，请检查网络',
								icon: 'none',
								duration: 3000
							});
							return;
						}
						
						// 上传文件到云存储
						this.doUploadAvatar(filePath);
					},
					fail: () => {
						// 即使网络检查失败，仍尝试上传
						this.doUploadAvatar(filePath);
					}
				});
			},
			
			// 执行头像上传
			doUploadAvatar(filePath, retryCount = 0) {
				const maxRetries = 2; // 最大重试次数
				
				uniCloud.uploadFile({
					filePath: filePath,
					cloudPath: `avatars/${this.userInfo._id}_${new Date().getTime()}.jpg`,
					success: (res) => {
						console.log('头像上传成功:', res);
						// 获取上传后的文件地址
						this.userInfo.avatar = res.fileID;
						uni.hideLoading();
						uni.showToast({
							title: '头像上传成功',
							icon: 'success'
						});
						
						// 上传成功后立即保存到数据库
						this.saveAvatarToDatabase(res.fileID);
					},
					fail: (err) => {
						console.error('头像上传失败', err);
						
						// 分析错误类型
						let errorMessage = '头像上传失败';
						if (err.errCode) {
							switch(err.errCode) {
								case -1:
									errorMessage = '网络连接失败，请检查网络';
									break;
								case -2:
									errorMessage = '文件不存在或已损坏';
									break;
								case -3:
									errorMessage = '文件格式不支持';
									break;
								case 40007:
									errorMessage = '文件大小超出限制';
									break;
								default:
									if (err.errMsg) {
										errorMessage = err.errMsg;
									}
							}
						}
						
						// 重试机制
						if (retryCount < maxRetries) {
							console.log(`头像上传失败，正在重试 ${retryCount + 1}/${maxRetries}`);
							setTimeout(() => {
								this.doUploadAvatar(filePath, retryCount + 1);
							}, 1000 * (retryCount + 1)); // 递增延迟
							return;
						}
						
						uni.hideLoading();
						uni.showModal({
							title: '上传失败',
							content: errorMessage + '，请重试',
							showCancel: true,
							cancelText: '取消',
							confirmText: '重试',
							success: (res) => {
								if (res.confirm) {
									this.uploadAvatar(filePath);
								}
							}
						});
					}
				});
			},
			
			// 保存头像到数据库
			async saveAvatarToDatabase(fileID) {
				const saveData = {
					userInfo: {
						_id: this.userInfo._id,
						avatar: fileID
					}
				};
				
				try {
					const userService = uniCloud.importObject('user-service');
					const res = await userService.saveUserProfile(saveData);
					
					if (res.code === 0) {
						console.log('头像保存到数据库成功');
						// 更新本地存储
						try {
							const userInfoStr = uni.getStorageSync('userInfo');
							if (userInfoStr) {
								const userData = JSON.parse(userInfoStr);
								userData.avatar = fileID;
								uni.setStorageSync('userInfo', JSON.stringify(userData));
							}
						} catch (e) {
							console.error('更新本地头像失败', e);
						}
					} else {
						console.error('头像保存到数据库失败:', res.message);
					}
				} catch (err) {
					console.error('头像保存到数据库失败', err);
				}
			},
			
			// 性别选择器变化
			bindGenderChange(e) {
				this.genderIndex = e.detail.value;
				this.userInfo.gender = parseInt(e.detail.value);
			},
			
			// 日期选择器变化
			bindDateChange(e) {
				this.userInfo.birthday = e.detail.value;
			},
			
			// 保存资料
			saveProfile() {
				// 表单验证
				if (!this.userInfo.nickname) {
					uni.showToast({
						title: '请输入姓名',
						icon: 'none'
					});
					return;
				}
				
				// 验证姓名只能包含中文和英文
				if (!/^[\u4e00-\u9fa5a-zA-Z]+$/.test(this.userInfo.nickname)) {
					uni.showToast({
						title: '姓名只能包含中文和英文',
						icon: 'none'
					});
					return;
				}
				
				if (this.userInfo.mobile && !/^1\d{10}$/.test(this.userInfo.mobile)) {
					uni.showToast({
						title: '手机号格式不正确',
						icon: 'none'
					});
					return;
				}
				
				if (this.userInfo.email && !/^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(this.userInfo.email)) {
					uni.showToast({
						title: '邮箱格式不正确',
						icon: 'none'
					});
					return;
				}
				
				uni.showLoading({
					title: '保存中...'
				});
				
				// 准备要保存的数据
				const saveData = {
					userInfo: {
						...this.userInfo,
						// 确保显式设置mobile和phone字段，以便后端可以更新登录方式
						mobile: this.userInfo.mobile,
						phone: this.userInfo.mobile, // 为兼容性保留phone字段
						// 确保包含ID，便于后端查找正确的用户
						_id: this.userInfo._id
					},
					token: uni.getStorageSync('token')
				};
				
				// 调用云对象保存资料
				(async () => {
					try {
						const userService = uniCloud.importObject('user-service');
						const res = await userService.saveUserProfile(saveData);
						
						if (res.code === 0) {
							// 保存成功，更新本地存储中的用户信息
							try {
								const userInfoStr = uni.getStorageSync('userInfo');
								if (userInfoStr) {
									const userData = JSON.parse(userInfoStr);
									// 更新用户信息
									const updatedUserInfo = {
										...userData,
										nickname: this.userInfo.nickname,
										realname: this.userInfo.nickname, // 将realname也设置为nickname
										mobile: this.userInfo.mobile,
										phone: this.userInfo.mobile, // 保持phone字段与mobile一致
										email: this.userInfo.email,
										gender: this.userInfo.gender,
										birthday: this.userInfo.birthday
									};
									// 保存更新后的信息到本地存储
									uni.setStorageSync('userInfo', JSON.stringify(updatedUserInfo));
									console.log('更新本地用户信息成功');
								}

								// 如果裁判员或监督员信息在响应中，更新本地数据
								if (res.data.refereeInfo) {
									this.refereeInfo = res.data.refereeInfo;
									this.levelIndex = this.refereeInfo.level || 0;
								}

								if (res.data.adminInfo) {
									this.adminInfo = res.data.adminInfo;
									this.adminLevelIndex = this.adminInfo.level || 0;
								}
							} catch (e) {
								console.error('更新本地用户信息失败', e);
							}
							
							uni.showToast({
								title: '保存成功',
								icon: 'success'
							});
						} else {
							uni.showToast({
								title: res.message || '保存失败',
								icon: 'none'
							});
						}
					} catch (err) {
						console.error('保存资料失败', err);
						uni.showToast({
							title: '保存失败',
							icon: 'none'
						});
					} finally {
						uni.hideLoading();
						// 确保无论成功或失败都会隐藏加载提示
						setTimeout(() => {
							uni.hideLoading();
						}, 100);
					}
				})();
			},
			// 获取学习统计
			async getLearningStatistics() {
				const token = uni.getStorageSync('token');
				if (!token) return;
				
				try {
					const learningService = uniCloud.importObject('learning-service');
					const res = await learningService.getLearningStatistics({
						token: token
					});
					
					if (res.code === 0) {
						this.learningStats = res.data;
						// 将学习时长（分钟）转换为小时
						this.learningStats.learningHours = Math.floor(this.learningStats.totalDuration / 60);
						if (this.learningStats.learningHours < 1 && this.learningStats.totalDuration > 0) {
							this.learningStats.learningHours = 1; // 不足1小时但有学习记录时，显示1小时
						}
					}
				} catch (err) {
					console.error('获取学习统计失败', err);
				}
			},
			
			// 导航到我的证书页面
			navigateToCertificates() {
				uni.showToast({
					title: '功能已被移除',
					icon: 'none'
				});
			}
		}
	}
</script>

<style>
	.container {
		min-height: 100vh;
		background-color: #f5f5f5;
		width: 100%;
		box-sizing: border-box;
	}
	
	.header {
		width: 100%;
		height: 400rpx;
		background: linear-gradient(to bottom, #1BAE76, #009F63);
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 0 30rpx;
		box-sizing: border-box;
	}
	
	.avatar-section {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-bottom: 30rpx;
		width: 100%;
		box-sizing: border-box;
	}
	
	.avatar {
		width: 160rpx;
		height: 160rpx;
		border-radius: 80rpx;
		border: 6rpx solid rgba(255, 255, 255, 0.6);
		margin-bottom: 20rpx;
	}
	
	.username {
		font-size: 36rpx;
		color: #FFFFFF;
		font-weight: bold;
		margin-bottom: 10rpx;
		word-wrap: break-word;
		word-break: break-all;
		text-align: center;
	}
	
	.user-info {
		font-size: 28rpx;
		color: rgba(255, 255, 255, 0.8);
		margin-bottom: 10rpx;
		word-wrap: break-word;
		word-break: break-all;
		text-align: center;
	}
	
	/* 信息卡片样式 */
	.card-section {
		margin: -60rpx 30rpx 30rpx;
		background-color: #FFFFFF;
		border-radius: 20rpx;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
		position: relative;
		z-index: 1;
		overflow: hidden;
		width: calc(100% - 60rpx);
		box-sizing: border-box;
	}
	
	.stat-row {
		display: flex;
		padding: 30rpx 0;
		border-bottom: 1rpx solid #f0f0f0;
		flex-wrap: wrap;
	}
	
	.stat-item {
		flex: 1;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		position: relative;
		min-width: 33.33%;
		margin-bottom: 20rpx;
	}
	
	.stat-value {
		font-size: 40rpx;
		color: #333333;
		font-weight: bold;
		margin-bottom: 10rpx;
	}
	
	.stat-label {
		font-size: 24rpx;
		color: #999999;
	}
	
	/* 菜单列表样式 */
	.menu-section {
		margin: 30rpx;
		background-color: #FFFFFF;
		border-radius: 20rpx;
		overflow: hidden;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
		width: calc(100% - 60rpx);
		box-sizing: border-box;
	}
	
	.menu-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 30rpx;
		border-bottom: 1rpx solid #f0f0f0;
	}
	
	.menu-item:last-child {
		border-bottom: none;
	}
	
	.item-left {
		display: flex;
		align-items: center;
	}
	
	.item-icon {
		width: 40rpx;
		height: 40rpx;
		margin-right: 20rpx;
	}
	
	.item-text {
		font-size: 30rpx;
		color: #333333;
		word-wrap: break-word;
		word-break: break-all;
	}
	
	/* 表单区域 */
	.form-section {
		background-color: #FFFFFF;
		border-radius: 12rpx;
		padding: 30rpx;
		margin-bottom: 30rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}
	
	.section-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333333;
		margin-bottom: 30rpx;
		padding-bottom: 20rpx;
		border-bottom: 1rpx solid #EEEEEE;
	}
	
	.form-item {
		display: flex;
		align-items: center;
		margin-bottom: 30rpx;
	}
	
	.form-label {
		width: 180rpx;
		font-size: 28rpx;
		color: #666666;
	}
	
	.form-input {
		flex: 1;
		height: 80rpx;
		border: 1rpx solid #DDDDDD;
		border-radius: 8rpx;
		padding: 0 20rpx;
		font-size: 28rpx;
		color: #333333;
	}
	
	.form-picker {
		flex: 1;
		height: 80rpx;
		border: 1rpx solid #DDDDDD;
		border-radius: 8rpx;
		padding: 0 20rpx;
		display: flex;
		align-items: center;
	}
	
	.picker-text {
		font-size: 28rpx;
		color: #333333;
	}
	
	/* 保存按钮 */
	.save-btn {
		width: 100%;
		height: 90rpx;
		line-height: 90rpx;
		background-color: #1BAE76;
		color: #FFFFFF;
		font-size: 32rpx;
		border-radius: 45rpx;
		margin-top: 10rpx;
		margin-bottom: 50rpx;
	}
	
	.form-input-readonly {
		flex: 1;
		height: 80rpx;
		border: 1rpx solid #DDDDDD;
		border-radius: 8rpx;
		padding: 0 20rpx;
		font-size: 28rpx;
		color: #333333;
		background-color: #f0f0f0;
		display: flex;
		align-items: center;
	}
	
	.required-mark {
		color: red;
		font-size: 24rpx;
		margin-left: 10rpx;
	}
	
	.section-tip {
		font-size: 24rpx;
		color: #999999;
		padding: 0 20rpx 20rpx;
		line-height: 1.4;
	}
	
	.no-certificate {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		height: 150rpx;
		font-size: 28rpx;
		color: #999999;
		text-align: center;
		border: 1rpx dashed #DDDDDD;
		border-radius: 8rpx;
		margin: 20rpx 0;
		background-color: #f9f9f9;
	}
	
	.certificate-hint {
		font-size: 24rpx;
		color: #1BAE76;
		margin-top: 10rpx;
		text-decoration: underline;
	}
</style> 